package db

import (
	"gorm.io/gorm"
	"strings"
)

type Config struct {
	DbName   string `yaml:"db_name"`
	Upgrade  bool   `yaml:"-"`
	LogLevel int    `yaml:"log_level"`
	AesKey   string `yaml:"aes_key"`
}

type Factory func(c *Config, cfg *gorm.Config) interface{}

var registry = make(map[string]Factory)

func RegDbType(name string, f Factory) {
	registry[name] = f
}

func OpenDB(cfg *Config, config *gorm.Config) gorm.Dialector {
	db := "mysql"
	if strings.HasSuffix(cfg.DbName, ".db") {
		db = "sqlite"
	}
	f := registry[db]
	if f != nil {
		return f(cfg, config).(gorm.Dialector)
	}
	return nil
}
